package com.yuma.tingshu.album.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import com.yuma.tingshu.album.mapper.AlbumStatMapper;
import com.yuma.tingshu.album.mapper.TrackInfoMapper;
import com.yuma.tingshu.album.mapper.TrackStatMapper;
import com.yuma.tingshu.common.constant.RabbitConstant;
import com.yuma.tingshu.common.constant.RedisConstant;
import com.yuma.tingshu.common.constant.SystemConstant;
import com.yuma.tingshu.model.album.AlbumStat;
import com.yuma.tingshu.model.album.TrackStat;
import com.yuma.tingshu.vo.album.TrackStatMqVo;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class AlbumListener {

    @Autowired
    private AlbumStatMapper albumStatMapper;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.ALBUM_STAT_QUEUE),
            exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            key = RabbitConstant.PLAY_STAT_RK
    ))
    public void albumStatChange(String jsonTrackStatMqVo, Channel channel, Message message) throws IOException {
        // 1.对象判空
        if (jsonTrackStatMqVo == null) {
            // 应答
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return;
        }

        // 2.转换成对象
        TrackStatMqVo trackStatMqVo = JSON.parseObject(jsonTrackStatMqVo, TrackStatMqVo.class);
        if (trackStatMqVo != null) {
            //3. 消息重复消费幂等性处理
            String key = RedisConstant.TRACK_STAT_IDEM + "_" + trackStatMqVo.getBusinessNo();
            // 设置成功继续，不成功
            if (!redisTemplate.opsForValue().setIfAbsent(key, "", 30 * 60, TimeUnit.SECONDS)) {
                //设置失败说明设置过
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                return;
            }
        } else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return;
        }
        try {
            switch (trackStatMqVo.getStatType()) {
                case SystemConstant.ALBUM_STAT_BROWSE:
                    // 更新album_stat的 stat_type=0403的那一项目
                    // 1.找到此专辑的统计数据
                    AlbumStat albumStat1 = albumStatMapper.selectOne(new LambdaQueryWrapper<AlbumStat>()
                            .eq(AlbumStat::getAlbumId, trackStatMqVo.getAlbumId())
                            .eq(AlbumStat::getStatType, SystemConstant.ALBUM_STAT_BROWSE));
                    if (albumStat1 != null) {
                        albumStat1.setStatNum(albumStat1.getStatNum() + trackStatMqVo.getCount());
                        albumStatMapper.updateById(albumStat1);
                    }
                    break;
                case SystemConstant.TRACK_STAT_PLAY:
                    TrackStat trackStat = trackStatMapper.selectOne(new LambdaQueryWrapper<TrackStat>()
                            .eq(TrackStat::getTrackId, trackStatMqVo.getTrackId())
                            .eq(TrackStat::getStatType, SystemConstant.TRACK_STAT_PLAY));
                    if (trackStat != null) {
                        trackStat.setStatNum(trackStat.getStatNum() + trackStatMqVo.getCount());
                        trackStat.setUpdateTime(new Date());
                        trackStatMapper.updateById(trackStat);
                    }
                    // 专辑播放数+1
                    AlbumStat albumStat = albumStatMapper.selectOne(new LambdaQueryWrapper<AlbumStat>()
                            .eq(AlbumStat::getAlbumId, trackStatMqVo.getAlbumId())
                            .eq(AlbumStat::getStatType, SystemConstant.ALBUM_STAT_PLAY));
                    if (albumStat != null) {
                        albumStat.setStatNum(albumStat.getStatNum() + trackStatMqVo.getCount());
                        albumStat.setUpdateTime(new Date());
                        albumStatMapper.updateById(albumStat);
                    }
                    break;
                case SystemConstant.TRACK_STAT_COLLECT:
                    TrackStat trackStat2 = trackStatMapper.selectOne(new LambdaQueryWrapper<TrackStat>()
                            .eq(TrackStat::getTrackId, trackStatMqVo.getTrackId())
                            .eq(TrackStat::getStatType, SystemConstant.TRACK_STAT_COLLECT));
                    if (trackStat2 != null) {
                        trackStat2.setStatNum(trackStat2.getStatNum() + trackStatMqVo.getCount());
                        trackStat2.setUpdateTime(new Date());
                        trackStatMapper.updateById(trackStat2);
                    }
                    break;
                case SystemConstant.TRACK_STAT_PRAISE:
                    TrackStat trackStat3 = trackStatMapper.selectOne(new LambdaQueryWrapper<TrackStat>()
                            .eq(TrackStat::getTrackId, trackStatMqVo.getTrackId())
                            .eq(TrackStat::getStatType, SystemConstant.TRACK_STAT_PRAISE));
                    if (trackStat3 != null) {
                        trackStat3.setStatNum(trackStat3.getStatNum() + trackStatMqVo.getCount());
                        trackStat3.setUpdateTime(new Date());
                        trackStatMapper.updateById(trackStat3);
                    }
                    break;
                case SystemConstant.TRACK_STAT_COMMENT:
                    TrackStat trackStat4 = trackStatMapper.selectOne(new LambdaQueryWrapper<TrackStat>()
                            .eq(TrackStat::getTrackId, trackStatMqVo.getTrackId())
                            .eq(TrackStat::getStatType, SystemConstant.TRACK_STAT_COMMENT));
                    if (trackStat4 != null) {
                        trackStat4.setStatNum(trackStat4.getStatNum() + trackStatMqVo.getCount());
                        trackStat4.setUpdateTime(new Date());
                        trackStatMapper.updateById(trackStat4);
                    }
                    break;
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 如果出现异常重试，先删除幂等性key
            // this.redisTemplate.delete(RedisConstant.TRACK_STAT_PREFIX + statMqVo.getBusinessNo());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            e.printStackTrace();
        }
    }
}
